import axios from 'axios'
import Vue from 'vue'
import { getToken } from '@/utils/auth'

function getQueryString(url, params){
  let tokenstr = getToken()
  if(tokenstr){
    tokenstr = `&token=${tokenstr}`
  } else {
    Promise.reject('/login')
    return
  }
  if(url.indexOf('?') > -1){
    for(let k in params) {
      url += `&${k}=${params[k]}`
    }
  } else {
    // 没有兼容queryString为空的情况
    let arr = params.keys()
    url += `?${arr[0]}=${params[arr[0]]}`
    if(arr[1]){
      for(let j = 1; j < arr.length; j++){
        url += '&' + arr[j] + '=' + params[arr[j]]
      }
    }
  }
  return url + tokenstr
}

function get(url, params){
  return axios.get(getQueryString(url, params))
}

function post(url, data){
  Object.assign(data, {
    token: getToken()
  })
  return axios.post(url, data)
}

export default { $get: get, $post: post }
